import { login } from "@/api/user/user";
import {
  getToken,
  setToken,
  removeToken,
  setUserInfo,
  getUserInfo,
  removeUserInfo
} from "@/utils/auth";

const user = {
  state: {
    token: getToken(),
    userInfo: getUserInfo() ? JSON.parse(getUserInfo()) : ""
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo;
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login({ phone: userInfo.code, Password: userInfo.password })
          .then(res => {
            const data = res.result;
            setToken(data.token);
            setUserInfo(data);
            commit("SET_TOKEN", data.token);
            commit("SET_USERINFO", data);
            resolve(res);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    // 登出
    LogOut({ commit }) {
      return new Promise(resolve => {
        // logout(state.token).then(() => {
        commit("SET_TOKEN", "");
        commit("SET_USERINFO", "");
        removeToken();
        removeUserInfo();
        resolve();
        // }).catch(error => {
        //   reject(error)
        // })
      });
    }
  }
};

export default user;
